package org.jeecg.util;

/**
 * @ClassName: SeqGenerator
 * @Description: 序列生成器
 * @author
 * @date 2013-11-4 上午11:18:35
 */
public class SeqGenerator
{
    /**
     * @Fields prefix : 序列前缀
     */
    private String prefix = "I";
    /**
     * @Fields cId : 客户端编号
     */
    private String cId;
    /**
     * @Fields dateFormat : 日期格式
     */
    private String dateFormat = "DATE8";
    /**
     * @Fields start : 起始值
     */
    private long start = 0L;
    /**
     * @Fields end : 最大值
     */
    private long end = 99999999L;

    /**
     * @Fields num : 集群部署编码
     */
    private String num = "00";

	public SeqGenerator() {}

    public SeqGenerator(String prefix, String cId, String dateFormat, String num)
    {
        this.prefix = prefix;
        this.cId = cId;
        this.dateFormat = dateFormat;
        this.num = num;
    }

    public SeqGenerator(String prefix, String cId, String dateFormat, long start, long end, String num)
    {
        this.prefix = prefix;
        this.cId = cId;
        this.dateFormat = dateFormat;
        this.start = start;
        this.end = end;
        this.num = num;
    }

    /**
     * @Title: next
     * @Description: 获取下一个值
     * @return
     * @return String 返回类型
     * @throws
     */
    public synchronized String next()
    {
        String seqStr = "";
        String date = "";
        String numStr = "";
        String yearStr = "";
        int yearInt = 1;
        if(dateFormat.equals("DATE8")){
            date = DateTimeUtil.getTodayChar8();

        }else if(dateFormat.equals("DATE14")){
            date = DateTimeUtil.getTodayChar14();

        }else if(dateFormat.equals("DATE17")){
            date = DateTimeUtil.getTodayChar17();

        }else if(dateFormat.equals("DATE12Short")){
            date = DateTimeUtil.getTodayChar12Short();

        }else if(dateFormat.equals("DATE11Short")){
            date = DateTimeUtil.getTodayChar12Short();
            yearInt = Integer.parseInt(date.substring(0,2))-14;
            //System.out.println(yearInt);
            date = "" + yearInt + date.substring(2);
            //System.out.println(date);
        }
        seqStr = this.prefix + this.cId + date;

        long count = ++ this.start;
        if(count >= this.end){
            this.start = 0L;
        }

        //补0
        int len = String.valueOf(this.end).length() - String.valueOf(count).length();
        if(len > 0){
            for(int i = 0; i < len; i ++){
                seqStr = seqStr.concat("0");
            }
        }

        //集群设置编码
        if("".equals(this.num)){
        	numStr = "00";
        }else{
        	numStr = this.num;
        }

        seqStr =  seqStr + count + numStr;

        return seqStr;
    }

    public static void main(String[] args)
    {
        SeqGenerator seq = new SeqGenerator("", "", "DATE14", 0L, 9999L,"00");
        for(int i=0;i<662;i++)
        	System.out.println(seq.next());
    }
}
